var map = new BMap.Map("map_container");
//初始化广州坐标
var point = new BMap.Point(114.405492,30.502934);
//地图平移缩放控件：默认左上方
map.addControl(new BMap.NavigationControl());
//比例尺控件，默认位于地图左下方，显示地图的比例关系
map.addControl(new BMap.ScaleControl());
map.centerAndZoom(point,12);
//添加鼠标滚动缩放
map.enableScrollWheelZoom(true);
//设置标注的图标
//var icon = new BMap.Icon("img/icon.jpg",new BMap.Size(100,100));
//设置标注的经纬度
var marker = new BMap.Marker(point);
//把标注添加到地图上
map.addOverlay(marker);

//地址解析类
var gc = new BMap.Geocoder();
//显示地址信息窗口
function showLocationInfo(pt, rs){
    var addComp = rs.addressComponents;
    $("#longitude").val(pt.lng);
    $("#latitude").val(pt.lat);
    console.log('经纬度：'+pt.lat+' '+pt.lng);
    $("#add-text1").val(pt.lat+','+pt.lng);
}
//删除标注
function deletePoint(){
    var allOverlay = map.getOverlays();
    for (var i = 0; i < allOverlay.length; i++){
        map.removeOverlay(allOverlay[i]);
    }
}

//根据选择框或输入框获取地址
var _area={
    //keyword:'',
    _areaLists:$(".areaLists"),
    _address:$("#address"),
    unChecked:function(val){
        return (val==''||typeof (val)=='undefined'||val==null||
            val=='省份'||val=='地级市'||val=='市、县级市')?false:true;
    },
    list:function(){
        var _joinArea='';
        for(var i=0;i<this._areaLists.length;i++){
            if(_area.unChecked(this._areaLists[i].value)){
                _joinArea+=this._areaLists[i].value;
            }
        }
        if(_area.unChecked(this._address.val())){
            _joinArea+=' '+this._address.val();
            //_joinArea=this._address.val();
        }
        return _joinArea;
    },
    init:function(){
        //绑定百度地图
        var _this=_area.list();
        //定义local
        var local = new BMap.LocalSearch(map, {
            renderOptions: {
                map: map,
                panel: "results",//结果容器id
                autoViewport: true,   //自动结果标注
                selectFirstResult: true  , //指定到第一个目标
                enableRouteSearchBox: true,
                enableRouteInfo:true
            },
            pageCapacity: 1
        });
        local.setSearchCompleteCallback(function (searchResult) {
            console.log(searchResult)
            var poi = searchResult.getPoi(0);
            //document.getElementById("result_").value = poi.point.lng + "," + poi.point.lat;
            map.centerAndZoom(poi.point, 12);
            gc.getLocation(poi.point, function(rs){
                showLocationInfo(poi.point, rs);
            });
        });
        local.search(_this);
    }
}

//搜索地址并赋值给form
$.fn.xcity = function(pName,cName,aName){

    var p = $(this).find('select[lay-filter=province]');

    var c = $(this).find('select[lay-filter=city]');

    var a = $(this).find('select[lay-filter=area]');

    var cityList = [];

    var areaList = [];

    showP(provinceList);

    showC(cityList);

    showA(areaList);

    function showP(provinceList) {
        p.html('');

        is_pName = false;

        for (var i in provinceList) {

            if(pName==provinceList[i].name){
                is_pName = true;
                cityList = provinceList[i].cityList;
                p.append("<option selected value='"+provinceList[i].name+"'>"+provinceList[i].name+"</option>")
            }else{
                p.append("<option value='"+provinceList[i].name+"'>"+provinceList[i].name+"</option>")
            }
        }
        if(!is_pName){
            cityList = provinceList[0].cityList;
        }

    }

    function showC(cityList) {

        c.html('');

        is_cName = false;

        for (var i in cityList) {
            if(cName==cityList[i].name){
                is_cName = true;
                areaList = cityList[i].areaList;
                c.append("<option selected value='"+cityList[i].name+"'>"+cityList[i].name+"</option>")
            }else{
                c.append("<option value='"+cityList[i].name+"'>"+cityList[i].name+"</option>")
            }
        }

        if(!is_cName){
            areaList = cityList[0].areaList;
        }
    }

    function showA(areaList) {
        a.html('');

        for (var i in areaList) {

            if(aName==areaList[i]){
                a.append("<option selected value='"+areaList[i]+"'>"+areaList[i]+"</option>")
            }else{
                a.append("<option value='"+areaList[i]+"'>"+areaList[i]+"</option>")
            }
        }
    }

    form.render('select');

    form.on('select(province)', function(data){
        pName = data.value;
        showP(provinceList);
        showC(cityList);
        showA(areaList);
        form.render('select');
        $("#address").val("");
        deletePoint();
        _area.init();
    });

    form.on('select(city)', function(data){
        cName = data.value;
        showC(cityList);
        showA(areaList);
        form.render('select');
        $("#address").val("");
        deletePoint();
        _area.init();
    });



}

//全局变量：存储address字符串长度做判断
var _thisLength='';
$("#address").keydown(function(){
    _thisLength=$(this).val().length;
})
$("#address").keyup(function(){
    var _newLength=$(this).val().length;
    var timer=setTimeout(function(){
        if(_thisLength<=_newLength){
            deletePoint();
            _area.init();
        }
        else{
            clearTimeout(timer);
        }
    },1000);
})
$("#address").blur(function(){
    deletePoint();
    _area.init();
})

_area.init();